import re
from typing import Any, Optional


class Validator:
    """验证工具类"""

    @staticmethod
    def is_valid_email(email: str) -> bool:
        """验证邮箱格式"""
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        return bool(re.match(pattern, email))

    @staticmethod
    def is_valid_phone(phone: str) -> bool:
        """验证手机号格式（中国大陆）"""
        pattern = r'^1[3-9]\d{9}$'
        return bool(re.match(pattern, phone))

    @staticmethod
    def is_valid_username(username: str) -> bool:
        """验证用户名格式"""
        # 用户名长度3-30个字符，只能包含字母、数字、下划线，不能以数字开头
        pattern = r'^[a-zA-Z_][a-zA-Z0-9_]{2,29}$'
        return bool(re.match(pattern, username))

    @staticmethod
    def is_strong_password(password: str) -> bool:
        """验证密码强度"""
        # 密码至少8位，包含大小写字母、数字和特殊字符
        if len(password) < 8:
            return False

        has_upper = bool(re.search(r'[A-Z]', password))
        has_lower = bool(re.search(r'[a-z]', password))
        has_digit = bool(re.search(r'\d', password))
        has_special = bool(re.search(r'[!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>?]', password))

        return has_upper and has_lower and has_digit and has_special

    @staticmethod
    def is_valid_tenant_code(code: str) -> bool:
        """验证租户编码格式"""
        # 租户编码3-50个字符，只能包含字母、数字、下划线和短横线
        pattern = r'^[a-zA-Z0-9_-]{3,50}$'
        return bool(re.match(pattern, code))

    @staticmethod
    def is_valid_ip(ip: str) -> bool:
        """验证IP地址格式"""
        pattern = r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
        return bool(re.match(pattern, ip))

    @staticmethod
    def is_valid_url(url: str) -> bool:
        """验证URL格式"""
        pattern = r'^https?://(?:[-\w.])+(?::[0-9]+)?(?:/(?:[\w/_.])*(?:\?(?:[\w&=%.])*)?(?:#(?:\w*))?)?$'
        return bool(re.match(pattern, url))

    @staticmethod
    def sanitize_string(value: str, max_length: Optional[int] = None) -> str:
        """清理字符串"""
        if not isinstance(value, str):
            return str(value)

        # 移除首尾空格
        value = value.strip()

        # 限制长度
        if max_length and len(value) > max_length:
            value = value[:max_length]

        return value

    @staticmethod
    def validate_file_type(filename: str, allowed_types: list) -> bool:
        """验证文件类型"""
        if not filename:
            return False

        file_ext = filename.split('.')[-1].lower()
        return file_ext in [ext.lower() for ext in allowed_types]

    @staticmethod
    def validate_file_size(file_size: int, max_size: int = 10 * 1024 * 1024) -> bool:
        """验证文件大小（默认最大10MB）"""
        return 0 < file_size <= max_size

    @staticmethod
    def is_valid_json(value: str) -> bool:
        """验证JSON格式"""
        import json
        try:
            json.loads(value)
            return True
        except (json.JSONDecodeError, TypeError):
            return False

    @staticmethod
    def validate_pagination_params(page: int, page_size: int, max_page_size: int = 100) -> tuple:
        """验证分页参数"""
        page = max(1, page)
        page_size = max(1, min(page_size, max_page_size))
        return page, page_size